package com.nlecloud.bc.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.nlecloud.bc.model.User;
import com.nlecloud.bc.util.JwtUtil;
import com.nlecloud.bc.util.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author warrior
 * @description 认证拦截器
 */
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {

    private ObjectMapper objectMapper;

    public AuthInterceptor(ObjectMapper objectMapper){
     this.objectMapper = objectMapper;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = AuthTokenStorage.getRequestHeaderToken(request);
        //判断token是否为空
        if(!StringUtils.isEmpty(token)){
            //解析验证token
            User user = JwtUtil.checkToken(token);
            if(user != null){
                //验证通过
                AuthTokenStorage.setUser(token,user);
                return true;
            }
        }
        //验证token无效
        response.setCharacterEncoding("UTF-8");
        ResponseUtil.responseWriter(objectMapper,response,"认证失败",401);
        return false;
    }
}
